from os import urandom
import blockchain
import nonce_source
import signature
import transaction



print('Mining difficulty: %s:%s' % (blockchain.DIFFICULTY_ORDER, blockchain.DIFFICULTY))


# nonce_source = nonce_source.NonceSource('/Users/jerryin/Desktop/pic/')
nonce_source = nonce_source.NonceSource('new')

blockchain.main_chain = [blockchain.mine_block(None, 'genesis', nonce_source, blockchain.DIFFICULTY_ORDER)]

key = signature.generate_key()

print(blockchain.main_chain[0].get_string())


def mineblocks(node):
    for i in range(1, 6):


        print(node + " mining...")
        transactions = []

        for j in range(0, i % 3 + 1):
            # t = transaction.sign_transaction('Transaction Data: %s' % encode(urandom(8)), key)
            t = transaction.sign_transaction('Transaction Data: %s' % str(urandom(8)), key)
            transactions.append(t)

        block_data = ''
        for t in transactions:
            block_data += t.get_string()+'\n'

        b = blockchain.mine_block(blockchain.main_chain[len(blockchain.main_chain) - 1], block_data, nonce_source, blockchain.DIFFICULTY_ORDER)
        for i in range(0,5):
            # chain_list[i].append(b)
            blockchain.main_chain.append(b)


        print(node + ':' + b.get_string())



print("chain start:" + ",".join(str(x) for x in blockchain.main_chain) + "chain end")
if __name__ == '__main__':
    while True:
        mineblocks("node1")